package com.bookshop.service;

import com.bookshop.aspect.exception.CustomException;
import com.bookshop.entity.response.R;
import com.bookshop.util.ImgNameUtils;
import com.bookshop.util.QiniuUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @author g2l
 * @create 2024-01-22 11:44
 */
@Component
public class PictureService {

    @Resource
    private QiniuUtils qiniuUtils;

    @Value("${qiniu.path}")
    private String url;

    public String upload(MultipartFile file) throws IOException {

        if (file.isEmpty()) {
            throw new CustomException( "上传文件为空");
        }
        // 获取文件(路径)名，这里的文件名其实是 /年/月/日/文件名 的格式，意思是还加上了文件夹路径的
        String fileName = ImgNameUtils.getRandomImgName(Objects.requireNonNull(file.getOriginalFilename()));
        // 获取文件流
        FileInputStream uploadFile = (FileInputStream) file.getInputStream();
        // 上传
        String path = qiniuUtils.upload(uploadFile, fileName);

        return "http://" + path;
    }
}
